package com.fry.mall.wallet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fry.mall.wallet.dto.RefundDTO;
import com.fry.mall.wallet.dto.UserConsumeDTO;
import com.fry.mall.wallet.dto.UserWalletDTO;
import com.fry.mall.wallet.entity.PaymentInfo;
import com.fry.mall.wallet.entity.RefundRecord;
import com.fry.mall.wallet.entity.UserWallet;
import com.fry.mall.wallet.entity.UserWalletLog;
import com.fry.mall.wallet.interceptor.WalletInterceptor;
import com.fry.mall.wallet.mapper.UserWalletMapper;
import com.fry.mall.wallet.response.ResponseResult;
import com.fry.mall.wallet.service.PaymentInfoService;
import com.fry.mall.wallet.service.RefundRecordService;
import com.fry.mall.wallet.service.UserWalletLogService;
import com.fry.mall.wallet.service.UserWalletService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author : FRY
 * @date : 2023-3-2
 */
@Service
public class UserWalletServiceImpl extends ServiceImpl<UserWalletMapper, UserWallet> implements UserWalletService {
    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RefundRecordService refundRecordService;

    @Autowired
    private UserWalletLogService userWalletLogService;

    /**
     * 获取用户钱包余额等信息
     *
     * @author: FRY
     * @date: 2023/03/02 22:38
     * @return: ResponseResult<UserWalletDTO>
     */
    @Override
    public UserWalletDTO getUserWalletBalance() {

        UserWallet userWallet = getUserWalletByUserId();
        if (userWallet != null) {
            UserWalletDTO userWalletDTO = new UserWalletDTO();
            BeanUtils.copyProperties(userWallet, userWalletDTO);
            return userWalletDTO;
        }
        return null;
    }

    /**
     * 处理用户消费
     *
     * @author: FRY
     * @date: 2023/03/02 23:37
     * @return: Boolean
     */
    @Override
    public Boolean dealConsumeOrder(UserConsumeDTO userConsumeDTO) {
        String userId = WalletInterceptor.threadLocal.get();

        UserWallet userWallet = getUserWalletByUserId();
        if (userWallet != null) {
            // 此次消费的金额
            BigDecimal totalAmount = userConsumeDTO.getTotalAmount();
            userWallet.setBalanceFee(userWallet.getBalanceFee().subtract(totalAmount));
            userWallet.setWalletOutcome(userWallet.getWalletOutcome().add(totalAmount));

            // 更新用户钱包信息
            int user_uuid = baseMapper.update(userWallet, new QueryWrapper<UserWallet>().eq("user_uuid", userId));

            // 保存消费记录
            PaymentInfo paymentInfo = new PaymentInfo();
            paymentInfo.setUserId(userId);
            paymentInfo.setOrderId(userConsumeDTO.getOrderId());
            paymentInfo.setOrderSn(userConsumeDTO.getOrderSn());
            paymentInfo.setPayStatus(1);
            paymentInfo.setReturnStatus(1);
            paymentInfo.setTotalAmount(totalAmount);
            paymentInfo.setTradeNo(userConsumeDTO.getTradeNo());
            paymentInfoService.save(paymentInfo);

            // 保存用户钱包流水明细
            UserWalletLog userWalletLog = new UserWalletLog();
            userWalletLog.setUserUuid(userId);
            userWalletLog.setTargetType(2);
            userWalletLog.setFee(userConsumeDTO.getTotalAmount());
            userWalletLog.setNumberId(userConsumeDTO.getOrderSn());
            userWalletLog.setStatus(1);
            userWalletLogService.save(userWalletLog);

            return true;
        }

        return null;
    }

    /**
     * 处理用户退款
     *
     * @param refundDTO
     * @author: FRY
     * @date: 2023/03/03 0:26
     * @return: Boolean
     */
    @Override
    public ResponseResult<String> dealRefund(RefundDTO refundDTO) {
        String userId = WalletInterceptor.threadLocal.get();

        // 1、确定退款是否合理，调用商家接口，经过商家同意后可退款
        Boolean agree = Boolean.valueOf("businessFeignService.checkRefund()");

        if (!agree) {
            // 商家不同意退款的情况
            return ResponseResult.showFailMsg("商家不同意退款");
        }

        // 2、确认退款，保存信息
        // 更新余额信息
        UserWallet userWallet = getUserWalletByUserId();
        if (userWallet != null) {
            userWallet.setBalanceFee(userWallet.getBalanceFee().add(refundDTO.getRefundAmount()));
        }

        // 保存退款记录(设定状态都正常)
        RefundRecord refundRecord = new RefundRecord();
        refundRecord.setRefundSn(refundDTO.getRefundSn());
        refundRecord.setRefundRemark(refundDTO.getRefundRemark());
        refundRecord.setRefundAmount(refundDTO.getRefundAmount());
        refundRecord.setOrderReturnId(refundDTO.getOrderReturnId());
        refundRecord.setRefundStatus(1);
        refundRecord.setRefundChannel(5);
        refundRecordService.save(refundRecord);

        // 保存用户钱包流水明细
        UserWalletLog userWalletLog = new UserWalletLog();
        userWalletLog.setUserUuid(userId);
        userWalletLog.setTargetType(2);
        userWalletLog.setFee(refundDTO.getRefundAmount());
        userWalletLog.setNumberId(refundDTO.getRefundSn());
        userWalletLog.setStatus(1);
        userWalletLogService.save(userWalletLog);

        return null;
    }

    /**
     * 获取用户账户钱包的变动明细数据
     * @author: FRY
     * @date: 2023/03/03 1:06
     * @return: List<UserWalletLog>
     */
    @Override
    public List<UserWalletLog> getBalanceChanges() {

        return null;
    }

    /**
     * 根据用户ID获取用户钱包信息
     * @author: FRY
     * @date: 2023/03/03 0:56
     * @return: UserWallet
     */
    public UserWallet getUserWalletByUserId() {
        String userId = WalletInterceptor.threadLocal.get();
        if (userId != null) {
            UserWallet userWallet = baseMapper.selectOne(new QueryWrapper<UserWallet>().eq("user_uuid", userId));
            return userWallet;
        }
        return null;
    }
}
